// Unit tests for tnet.js


//
// First make sure required modules are loaded
//

if (typeof require !== 'undefined') {

  if (typeof phantom !== 'undefined') {
    var system = require('system');
    // Inject libraries
    for (var i=1; i<system.args.length; ++i) {
      console.log("Injecting " + system.args[i]);
      phantom.injectJs(system.args[i]);
    }
    console.log("Done Injecting");
    console.log("");

  } else {
    // Running in Node with common JS modules.
    var jsUnity = require('jsunity-0.6'),
        tnet = require('tnet');
  }

}  // else: no module system with v8shell, use multiple args



//
// Then set jsUnity.log.
//


// NOTES:
// - console.log not defined in v8 shell.
// - print is a STUB in PhantomJS, ugh.  It's defined but doesn't do anything.

if (typeof console !== 'undefined' && typeof console.log !== 'undefined') {
  // Crazy bug in PhantomJS: can't do 'console.log = jsUnity.log'
  jsUnity.log = function(s) { console.log(s); }
} else if (typeof print !== 'undefined') {
  jsUnity.log = print;  // Windows?  cscript-shell.  v8shell might have it too.
}

// my own function?
var debug_log = jsUnity.log;

var module = function() {

// Data for multiple tests
var foo = function(value) { return 'foo'; };

// Test for public APIs
var PublicTest = {
  suiteName: 'PublicTest',

  testDumpLine: function () {
    var s = tnet.dump_line('foo');
    jsUnity.assertions.assertEqual(s, '3:foo\n');
  },

  testDump: function () {
    var s = tnet.dumps('foo');
    jsUnity.assertions.assertEqual(s, '3:foo$');

    var s = tnet.dumps(1);
    jsUnity.assertions.assertEqual(s, '1:1^');
  },

  // Clever:
  // http://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript

  testUnicode: function () {
    // Unicode
    jsUnity.log("hello \u00B5");
    jsUnity.log("\u00B5".length);
    jsUnity.log(encodeURIComponent("\u00B5"));
  },

  testBloads: function () {
    jsUnity.log('YOOOOOOOO'); 
    // {foo: bar}
    var obj = tnet.b_loads('12:3:foo,3:bar,}');
    jsUnity.assertions.assertEqual('bar', obj.foo);
  },

  testBdumps: function () {
    var buf = tnet.b_dumps('foo');
    jsUnity.assertions.assertEqual('3:foo,', buf);

    var buf = tnet.b_dumps({foo: 'bar'});
    jsUnity.assertions.assertEqual('12:3:foo,3:bar,}', buf);
  }
};

var results = jsUnity.run(PublicTest);

jsUnity.log("");
jsUnity.log("DONE");

if (typeof phantom !== 'undefined') {
  phantom.exit();
}

}();
